<template>
    <div class="product">
        <el-button style="margin-bottom: 10px" @click="changeDialog(true)" type="primary">添加商品</el-button>
        <div>
            <el-table :data="productList" style="width: 100%">
                <el-table-column prop="id" label="商品编号" width="100"></el-table-column>
                <el-table-column prop="name" label="商品名称" width="200"></el-table-column>
                <el-table-column prop="price" label="商品价格" width="100">
                    <template #default="scope">￥{{ scope.row.price }}</template>
                </el-table-column>
                <el-table-column prop="category_id" label="商品分类" width="100">
                </el-table-column>
                <el-table-column prop="stock" label="商品库存" width="100"></el-table-column>
                <el-table-column prop="description" label="商品简介">
                    <template #default="scope">
                        <div v-html="scope.row.description"></div>
                    </template>
                </el-table-column>
                <el-table-column prop="image" label="商品图片">
                    <template #default="scope">
                        <img :src="scope.row.picture" alt="">
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" @click="editProduct(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="deleteProduct(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background :total="total" :current-page.sync="page" :page-size="pageSize"
                :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentChange" @size-change="handleSizeChange"
                style="margin-top: 20px;justify-content:flex-end;" />
        </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isAddProduct ? '新增商品' : '编辑商品'" width="700" :destroy-on-close="true">
        <el-form ref="productForm" :model="productData" :rules="rules" label-width="80px">
            <el-form-item label="商品名称" prop="name">
                <el-input placeholder="请输入商品名称" :maxLength="20" v-model.trim="productData.name" />
            </el-form-item>
            <el-form-item label="分类名称" prop="category_id">
                <el-select v-model="productData.category_id" placeholder="请选择分类名称">
                    <el-option v-for="item in categoryList" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input placeholder="请输入商品价格" v-model.number="productData.price" />
            </el-form-item>
            <el-form-item label="商品图片">
                <el-upload ref="uploadRef" :auto-upload="false" :on-change="handlePictureChange"
                    :on-error="handlePictureError">
                    <el-button type="primary">选择图片</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            图片文件大小不能超过 500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="商品相册">
                <el-upload class="uploadAlbum" multiple ref="uploadAlbumRef" :auto-upload="false"
                    :on-change="handleAlbumChange" list-type="picture-card">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
                <el-input placeholder="请输入商品库存" v-model.number="productData.stock" clearable />
            </el-form-item>
            <el-form-item label="商品规格" prop="spec">
                <el-input placeholder="请输入商品规格" clearable v-model.trim="productData.spec" />
            </el-form-item>
            <el-form-item label="商品简介" prop="description">
                <div class="ql-container">
                    <QuillEditor ref="myQuillEditor" :options="editorOption" contentType="html"
                        v-model:content="productData.description" />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit(isAddProduct)">提交</el-button>
                <el-button @click="changeDialog(true)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getProductListService, addProductService, updateProductService, deleteProductService } from '@/apis/product'
import { getCategoryListService } from '@/apis/category';
import { uploadService } from '@/apis/upload';
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox } from 'element-plus';
const dialogVisible = ref(false)
const isAddProduct = ref(true)
const productList = ref([])
const productData = ref({
    name: '',
    category_id: '',
    price: '',
    stock: '',
    description: '',
    picture: '',
    spec: '',
    album: []
})
// 表单校验规则
const rules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 20, message: '商品名称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    category_id: [
        { required: true, message: '请选择分类名称', trigger: 'change' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', message: '请输入正确的商品价格', trigger: 'blur' }
    ],
    stock: [
        { required: true, message: '请输入商品库存', trigger: 'blur' },
        { type: 'number', message: '请输入正确的商品库存', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入商品简介', trigger: 'blur' }
    ]
}
// 富文本编辑器配置
const editorOption = {
    modules: {
        toolbar: [
            ['bold', 'underline', 'italic', 'strike']
        ]
    },
    placeholder: '请输入内容...'
}
// 分类列表
const categoryList = ref([])
// 获取分类列表
const getCategoryList = async () => {
    const res = await getCategoryListService();
    categoryList.value = res.data.filter(item => {
        return item.pid !== 0;
    })
}
getCategoryList();
//分页模型
const page = ref(1)
const pageSize = ref(5)
const total = ref(0)
// 获取商品列表
const getProductList = async () => {
    let params = {
        page: page.value,
        pagesize: pageSize.value
    }
    const res = await getProductListService(params);
    total.value = res.data.total;
    productList.value = res.data.list;
}
getProductList();
const changeDialog = (isAdd) => {
    isAddProduct.value = isAdd;
    // 清空表单数据
    productData.value = {
        name: '',
        category_id: '',
        price: '',
        stock: '',
        description: '',
        picture: '',
        spec: '',
        album: []
    }
    dialogVisible.value = !dialogVisible.value;
}
const handleCurrentChange = (currentPage) => {
    page.value = currentPage;
    getProductList();
}
const handleSizeChange = (size) => {
    pageSize.value = size;
    getProductList();
}

// 编辑商品
const editProduct = (row) => {
    // 打开弹窗
    changeDialog(false);
    // 设置表单数据
    productData.value = { id: row.id, name: row.name, category_id: row.category_id, price: row.price, stock: row.stock, description: row.description, spec: row.spec };
}
// 删除商品
const deleteProduct = (id) => {
    ElMessageBox.confirm('确认删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let res = await deleteProductService({ id: id });
        ElMessage.success(res.errmsg);
        getProductList();
    }).catch(() => {
    });
}
// 相册选择
const albumList = ref([])
const handleAlbumChange = (uploadFile) => {
    albumList.value.push(uploadFile);
}
// 选择图片
const file = ref(null)
const handlePictureChange = (uploadFile) => {
    file.value = uploadFile;
}
const handlePictureError = (err) => {
    console.log(err);
}
// 新增商品
const productForm = ref(null)
const handleSubmit = (isAdd) => {
    productForm.value.validate(async (valid) => {
        if (!valid) {
            return false;
        }
        // 上传图片
        if (file.value) {
            let res = await uploadService(file.value.raw, 'goods_picture');
            productData.value.picture = res.data.savepath;
        }
        // 上传相册
        if (albumList.value.length > 0) {
            let album = [];
            for (let i = 0; i < albumList.value.length; i++) {
                let res = await uploadService(albumList.value[i].raw, 'goods_album');
                album.push(res.data.savepath);
            }
            productData.value.album = album;
        }
        productData.value.id = isAdd ? '' : productData.value.id;
        let res = await (isAdd ? addProductService(productData.value) : updateProductService(productData.value));
        changeDialog(true);
        getProductList();
        ElMessage.success(res.errmsg);
    })
}
</script>
<style scoped>
img,
:deep(img),
:deep(.el-upload-list__item) {
    max-width: 80px;
    max-height: 80px;
    object-fit: cover;
}

.ql-container {
    width: 100%;
    height: max-content;
}

:deep(.ql-toolbar) {
    padding: 0;
}

:deep(.ql-editor) {
    min-height: 70px;
}

:deep(.uploadAlbum .el-upload) {
    width: 80px;
    height: 80px;
}

:deep(.el-upload .el-icon) {
    font-size: 20px;
}
</style>